//
//  CXStatusPhotoView.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/24.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit
import SDWebImage
//import SDPhotoBrowser

private let CXStatusPhotoCellID = "photocellid"
private let CXStatusPhotoMargin:CGFloat = 5
//转成Int是为了抛掉无限循环小数 防止因为不确定而导致cell的布局错误
//private let CXStatusPhotoWH = CGFloat(Int(SCREENW - 2 * CXComponentsInMargin - 2 * CXStatusPhotoMargin) / 3)

class CXStatusPhotoView: UICollectionView {

    /// 图片信息数组
    var pic_urls:[CXStatusPhotoInfo]? {
        
        didSet {
            //由于复用的缘故，pic的数量反复变化，因此size会不断被更新。因此约束不要使用make来操作
            self.snp_updateConstraints { (make) -> Void in
                let size = getViewSize(pic_urls!.count)
                //直接 make.size没法显示 SnapKit的bug？？？？
                make.width.equalTo(size.width)
                make.height.equalTo(size.height)
                //make.size.equalTo(size)
            }
            //刷新数据
            self.reloadData()
        }
    }
    private lazy var CXStatusPhotoWH:CGFloat = {
        let tmp1 = CGFloat(2 * CXComponentsInMargin) + CGFloat(2 * CXStatusPhotoMargin)
        let tmp2 = (SCREENW - tmp1) / 3
        return CGFloat(Int(tmp2))
    }()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //禁止滚动到顶部。防止点击导航栏时，首页的tableView无法滚动到顶部的情况
        scrollsToTop = false
        let flowlayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowlayout.itemSize = CGSize(width: CXStatusPhotoWH, height: CXStatusPhotoWH)
        flowlayout.minimumInteritemSpacing = CXStatusPhotoMargin
        flowlayout.minimumLineSpacing = CXStatusPhotoMargin
        
        //注册
        registerClass(CXStatusPhotoCell.self, forCellWithReuseIdentifier: CXStatusPhotoCellID)
        dataSource = self
        delegate = self
    }
}
// MARK: - 设置UI
extension CXStatusPhotoView {

    //返回图片区域的尺寸
    private func getViewSize(count: Int) -> CGSize {
        
        if count == 1 {
            let pic_url = pic_urls!.last!.thumbnail_pic!
            //从缓存取图片
            if let imgOne = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(pic_url) {
                //获取该图片尺寸
                var imgSize = imgOne.size
                
                if imgSize.width < 80 {
                    let newH = (80 / imgSize.width) * imgSize.height
                    imgSize.width = 80
                    imgSize.height = newH > 150 ? 150 : newH   //防止图片太长
                } else if imgSize.width > 260 {
                    let newH = (260 / imgSize.width) * imgSize.height
                    imgSize.width = 260
                    imgSize.height = newH
                }
                //由于默认itemSize比 80 大，因此在这里要修改itemSize
                let fl = collectionViewLayout as! UICollectionViewFlowLayout
               // print("one picture size is : \(imgSize)")
                fl.itemSize = imgSize
                return imgSize
            }
        } else {
            //图片个数不为 1. 把itemSize改回来
            let fl = collectionViewLayout as! UICollectionViewFlowLayout
            fl.itemSize = CGSize(width: CXStatusPhotoWH, height: CXStatusPhotoWH)
        }
        let col = count == 4 ? 2 : (count <= 3 ? count : 3)
        let row = (count + 2) / 3
        
        let width = CXStatusPhotoWH * CGFloat(col) + CXStatusPhotoMargin * CGFloat(col - 1)
        let height = CXStatusPhotoWH * CGFloat(row) + CXStatusPhotoMargin * CGFloat(row - 1)
        return CGSize(width: width, height: height)
    }
}
// MARK: - 实现数据源方法和代理方法,实现图片轮播视图的代理
extension CXStatusPhotoView: UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //print(pic_urls?.count ?? 0)
        return pic_urls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CXStatusPhotoCellID, forIndexPath: indexPath) as! CXStatusPhotoCell
        cell.photourl = pic_urls![indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = pic_urls?.count ?? 0
        browser.delegate = self
        browser.currentImageIndex = indexPath.item
        browser.show()
    }
    //必须实现
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let cell = cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! CXStatusPhotoCell
        return cell.CXImageV.image
    }
    //可选实现 以来显示轮播中的中等尺寸图片
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let picUrl = pic_urls![index].thumbnail_pic!
        return NSURL(string: picUrl.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle"))
    }
}
private class CXStatusPhotoCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var photourl: CXStatusPhotoInfo? {
        
        didSet {
            //进行下载.这里是可以进行优化的（如果提前获取了图片的尺寸）
            CXImageV.sd_setImageWithURL(NSURL(string: photourl!.thumbnail_pic!), placeholderImage: UIImage(named:"timeline_image_placeholder"))
            
            //是否该贴gif标签
            gifView.hidden = !photourl!.thumbnail_pic!.hasSuffix(".gif")
        }
    }
    
    private lazy var CXImageV: UIImageView = {
        let imageV = UIImageView()
        //修改内容模式
        imageV.contentMode = .ScaleAspectFill
        //是否裁剪
        imageV.clipsToBounds = true
        //不留占位图片?
        return imageV
    }()
    /// gif标签
    private lazy var gifView: UIImageView = {
        let gifv = UIImageView(image: UIImage(named: "timeline_image_gif"))
        return gifv
    }()
}
extension CXStatusPhotoCell {
    private func setupUI() {
        
        contentView.addSubview(CXImageV)
        contentView.addSubview(gifView)
        //设置约束
        CXImageV.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        gifView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(CXImageV)
            make.trailing.equalTo(CXImageV)
        }
    }
}